<script lang="ts">
	import { Slider } from 'bits-ui';
	import Play from '../../icons/Play.svelte';
	import Pause from '../../icons/Pause.svelte';
	import { onMount } from 'svelte';

	export let audioSrc;

	let progressValue = [0];
	let playStatus = false;
	let audioTime = '';
	let playTime = '00:00';
	let Audio;

	// 时分秒转换
	const transTime = (value) => {
		let time = '';
		let h = parseInt(`${value / 3600}`);
		value %= 3600;
		let m = parseInt(`${value / 60}`);
		let s = parseInt(`${value % 60}`);
		if (h > 0) {
			time = formatTime(h + ':' + m + ':' + s);
		} else {
			time = formatTime(m + ':' + s);
		}

		return time;
	}
	// 补零
	const formatTime = (value) => {
		let time = '';
		let s = value.split(':');
		let i = 0;
		for (; i < s.length - 1; i++) {
			time += s[i].length === 1 ? '0' + s[i] : s[i];
			time += ':';
		}
		time += s[i].length === 1 ? '0' + s[i] : s[i];

		return time;
	}

	onMount(() => {
		Audio = document.querySelector('#audio');

		Audio.addEventListener('loadedmetadata', (e) => {
			audioTime = transTime(e.target.duration);
		});

		Audio.addEventListener('timeupdate', (e) => {
			playTime = transTime(e.target.currentTime);
			progressValue = [Math.round(e.target.currentTime / Audio.duration * 100)];
		});

		Audio.addEventListener('ended', (e) => {
			playTime = '00:00'
			progressValue = [0];
			playStatus = false;
		});
	})

	const Skip = num => {
		Audio.currentTime = Math.round(Audio.duration * num / 100);
		progressValue = [num];
	};

	const playAudio = () => {
		playStatus = !playStatus;
		if (playStatus) {
			Audio?.play();
		} else {
			Audio?.pause();
		}
	}
</script>

<div>
	<audio id="audio" src={audioSrc} class="hidden" />

	<div class="flex items-center justify-start">
		<button on:click={playAudio}>
			{#if playStatus}
				<Pause />
			{:else}
				<Play />
			{/if}
		</button>

		<span class="text-[#E95513] mx-4">
			{playTime}
		</span>

		<div class="w-[320px]">
			<Slider.Root
				bind:value={progressValue}
				let:thumbs
				class="relative flex w-full touch-none select-none items-center"
				onValueChange={Skip}
			>
				<span class="relative h-0.5 w-full grow overflow-hidden rounded-full bg-[#858EAD]">
					<Slider.Range class="absolute h-full bg-[#E95513]" />
				</span>
				{#each thumbs as thumb}
					<Slider.Thumb
						{thumb}
						class="block size-[16px] cursor-pointer rounded-full bg-[#E95513] shadow  transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-foreground focus-visible:ring-offset-2 active:scale-98 disabled:pointer-events-none disabled:opacity-50"
					/>
				{/each}
			</Slider.Root>
		</div>

		<span class="text-[#858EAD] mx-2">
			{audioTime}
		</span>
	</div>
</div>
